package com.tulele.vtool.handler;

import com.google.common.collect.Maps;
import com.tulele.vtool.model.LookArticleInfo;
import com.tulele.vtool.model.PunchClockArticleInfo;
import com.tulele.vtool.model.UserInfo;
import com.tulele.vtool.model.WxNotifyMsgSetInfo;
import com.tulele.vtool.model.logEntity.PageDetailLog;
import com.tulele.vtool.model.respEntity.RespData;
import com.tulele.vtool.model.respEntity.ReturnCode;
import com.tulele.vtool.service.ConnectionInfoService;
import com.tulele.vtool.service.IArticleInfoService;
import com.tulele.vtool.service.IUserInfoService;
import com.tulele.vtool.service.IUserPunchClockInfoService;
import com.tulele.vtool.utils.DateUtil;
import com.tulele.vtool.utils.SysConstant;
import com.tulele.vtool.utils.ToolUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@RestController
@Slf4j
public class UserPunchClockHandler {

    @Autowired
    private IUserPunchClockInfoService userPunchClockInfoService;

    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private IArticleInfoService articleInfoService;

//    @Value("${spring.profiles.active}")
//    private String springProfilesActive;

    @Autowired
    private ConnectionInfoService connectionInfoService;


    @GetMapping(value = "/getCurPunchClockArticleInfo", produces="application/json;charset=UTF-8")
    public RespData getCurPunchClockArticleInfo(@RequestHeader("userId") String userId,@RequestHeader("identifying") String springProfilesActive,
                                                @RequestParam(value="clockUserId", required=false)String clockUserId,
                                                @RequestParam(value="clockArticleId", required=false)String clockArticleId) {

        log.info("********** Action getCurPunchClockArticleInfo"+",[userId]="+userId+",[clockUserId]="+clockUserId+",[clockArticleId]="+clockArticleId);
        log.info("[userId] =" + userId + " [clockUserId] = " + clockUserId + " [clockArticleId] = " + clockArticleId);

        Map<String, Object> resultMap = Maps.newHashMapWithExpectedSize(8);

        //当clockUserId不为空时，拿clockUserId去传入签到中，所以分享出来的链接要带clockUserId，点的人就可以正常看到是谁的，也不会产生签到记得
        //当clockUserId为空时，拿userId去传入签到中，当看了分享的人点“免费变化我的签名”时，在链接中把clockUserId去掉，就可以按当前用户签到
        int finalUserId = Integer.parseInt(userId);
        if (StringUtils.isNotBlank(clockUserId) && StringUtils.isNumeric(clockUserId)) {
            finalUserId = Integer.parseInt(clockUserId.trim());

            //20200401 添加邀请按钮设置
            WxNotifyMsgSetInfo userNotifyMsgSetInfo= userInfoService.getUserNotifySetInfo(finalUserId);
            if(userNotifyMsgSetInfo!=null){
                resultMap.put("inviteSetStatus", userNotifyMsgSetInfo.getInviteSetStatus());
            }

        }

        PunchClockArticleInfo punchClockArticleInfo = null;
        if (StringUtils.isNotBlank(clockArticleId) && StringUtils.isNumeric(clockArticleId)) {
            punchClockArticleInfo = userPunchClockInfoService.getPunchClockArticleInfoById(Integer.parseInt(clockArticleId));
        } else {
            punchClockArticleInfo = userPunchClockInfoService.getUserPunchClockArticleInfo();
        }

        if (StringUtils.isNotBlank(clockUserId) && !Objects.equals(userId, clockUserId)) {

            LookArticleInfo lookArticleInfo = new LookArticleInfo();
            lookArticleInfo.setUserId(Integer.parseInt(userId));
            lookArticleInfo.setOtherUserId(Integer.parseInt(clockUserId));
            lookArticleInfo.setArticleId(punchClockArticleInfo.getId());
            log.info("********** Action getCurPunchClockArticleInfo LookArticleInfo");
            UserInfo lookUserInfo = userInfoService.getUserMainInfo(Integer.parseInt(userId));

            articleInfoService.lookOtherUserPunchClockArticle(lookArticleInfo, punchClockArticleInfo, lookUserInfo.getNickName());

        }

        int finalClockArticleId = punchClockArticleInfo.getId();
        Date clockTime = punchClockArticleInfo.getClockArticleTime();
//        Date clockTime =DateUtil.getCurDate();//20200111 hyl

        int clockDays = userPunchClockInfoService.userPunchClockProcess(finalUserId, finalClockArticleId, clockTime);

        UserInfo userInfo = userInfoService.getUserMainInfo(finalUserId);

        HashMap<String, Object> userInfoMap = Maps.newHashMapWithExpectedSize(7);
        userInfoMap.put("userId", userInfo.getUserId());
        userInfoMap.put("avatarUrl", userInfo.getAvatarUrl());
        userInfoMap.put("nickName", userInfo.getNickName());
        userInfoMap.put("vipStatus", Optional.ofNullable(userInfo.getVipStatus()).orElse(0));
        userInfoMap.put("qrcodeUrl", userInfo.getQrcodeUrl());
        userInfoMap.put("blockState", userInfo.getBlockState());

        int concernStatus = Optional.ofNullable(userInfoService.getUserConcernStatus(Integer.parseInt(userId))).orElse(0);
        userInfoMap.put("concernStatus", concernStatus);


        resultMap.put("userInfo", userInfoMap);

        //处理标题
        //true-上午 false-下午
//        boolean resultStatus = ToolUtil.getAmPmTimePeriodStatus();

        StringBuffer title = new StringBuffer();
        title.append("【");

        /*if (resultStatus) {
            title.append("早安\uD83C\uDF24");
        } else {
            title.append("晚安\uD83C\uDF24");
        }*/

        int timeType = punchClockArticleInfo.getClockArticleTimeType().intValue();// 打卡文章时间类型 1-早安打卡 2-晚安打卡
        if (timeType == 1) {
            title.append("早安\uD83C\uDF24");
        } else if (timeType == 2) {
            title.append("晚安\uD83C\uDF24");
        }

        title.append("第");
        title.append(clockDays);
        title.append("天】");
        title.append(userInfo.getNickName());

        String clockArticleTitle = punchClockArticleInfo.getClockArticleTitle();
        if (StringUtils.isNotBlank(clockArticleTitle)) {

            title.append(": ");
            title.append(clockArticleTitle);

        } else {

            title.append("与");
            int totalClockDays = Optional.ofNullable(userPunchClockInfoService.getTotalUserPunchClockDays()).orElse(0);
            title.append(172668 + totalClockDays);
            title.append("人一起坚持打卡，传播正能量");

        }

        //生成文章描述
        String articleContent = punchClockArticleInfo.getClockArticleContent();
        if (StringUtils.isNotBlank(articleContent)) {

            int articleConteLength = articleContent.length();
            if (articleConteLength > 40) {
                punchClockArticleInfo.setClockArticleDesc(articleContent.substring(0, 40));
            } else {
                punchClockArticleInfo.setClockArticleDesc(articleContent);
            }

        }

        Map<String, Object> punchClockArticleInfoMap = Maps.newLinkedHashMapWithExpectedSize(9);
        punchClockArticleInfoMap.put("id", punchClockArticleInfo.getId());
        punchClockArticleInfoMap.put("clockArticleTitle", title);
        punchClockArticleInfoMap.put("clockArticleImgUrl", punchClockArticleInfo.getClockArticleImgUrl()+"?"+ SysConstant.OSS_PAR);//oss 压缩
        punchClockArticleInfoMap.put("clockArticleThumbnailUrl", punchClockArticleInfo.getClockArticleThumbnailUrl()+"?"+ SysConstant.OSS_PAR_80_80);//oss 压缩
        punchClockArticleInfoMap.put("clockArticleAudioUrl", punchClockArticleInfo.getClockArticleAudioUrl());
        punchClockArticleInfoMap.put("clockArticleContent", punchClockArticleInfo.getClockArticleContent());
        punchClockArticleInfoMap.put("clockArticleDesc", punchClockArticleInfo.getClockArticleDesc());
        punchClockArticleInfoMap.put("clockArticleTime", punchClockArticleInfo.getClockArticleTime());
        punchClockArticleInfoMap.put("clockArticleTimeType",punchClockArticleInfo.getClockArticleTimeType());//1早安 2晚安

        resultMap.put("punchClockArticleInfo", punchClockArticleInfoMap);
        resultMap.put("clockDays", clockDays);
        resultMap.put("curUserId", Integer.parseInt(userId));

        int userConcernStatus = Optional.ofNullable(userInfoService.getUserConcernStatus(Integer.valueOf(userId))).orElse(0);
        resultMap.put("concernStatus", userConcernStatus);

        // 添加访问记录
        this.addAccessRecord(Integer.valueOf(userId),springProfilesActive);

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setData(resultMap);
        respData.setMsg("成功");
        return respData;

    }

    /**
     * 异步添加用户访问记录
     * @param userId
     */
    @Async
    void addAccessRecord(Integer userId,String springProfilesActive){
        PageDetailLog log = new PageDetailLog();
        log.setAccessTime(new Date());
        log.setGzhCode(springProfilesActive);
        log.setPageName("早晚安打卡");
        log.setUserId(userId);
        this.connectionInfoService.addAccessRecord(log);
    }

}
